<script setup>
import { useCartStore, useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'
import { onMounted } from 'vue'
import { useRouter } from 'vue-router'

const cartStore = useCartStore()
const userStore = useUserStore()
const router = useRouter()

// 检查登录状态
onMounted(() => {
  if (!userStore.userInfo.token) {
    ElMessage.warning('请先登录后再查看购物车')
    router.push('/login')
    return
  }
  // 初始化购物车数据
  cartStore.initCart()
})

// 修改数量变更方法
const handeChangeCount = async (id, count) => {
  if (!userStore.userInfo.token) {
    ElMessage.warning('请先登录后再操作购物车')
    router.push('/login')
    return
  }

  try {
    await cartStore.changeCount(id, count)
  } catch (error) {
    ElMessage.error(error.message)
  }
}

// 修改单选操作方法
const handleCheck = async (id, selected) => {
  try {
    await cartStore.singleCheck(id, selected)
  } catch (error) {
    ElMessage.error(error.message)
  }
}

// 修改全选操作方法
const handleAllCheck = async (selected) => {
  try {
    await cartStore.allCheck(selected)
  } catch (error) {
    ElMessage.error(error.message)
  }
}

// 删除购物车商品
const deleteCart = async (item) => {
  if (!userStore.userInfo.token) {
    ElMessage.warning('请先登录后再操作购物车')
    router.push('/login')
    return
  }

  try {
    await cartStore.deleteCart(item.id)
    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.error(error.message || '删除失败，请重试')
  }
}

// 图片加载错误处理
const handleImageError = (event) => {
  event.target.src = '/src/assets/images/none.png'
}

// 去结算
const goToCheckout = () => {
  if (!userStore.userInfo.token) {
    ElMessage.warning('请先登录后再进行结算')
    router.push('/login')
    return
  }

  if (cartStore.selectedCount === 0) {
    ElMessage.warning('请选择要结算的商品')
    return
  }

  // 跳转到结算页面
  router.push('/checkout')
}
</script>

<template>
  <div class="xtx-cart-page">
    <div class="container m-top-20">
      <div class="cart">
        <table>
          <thead>
            <tr>
              <th width="120">
                <el-checkbox
                  :modelValue="cartStore.isAll"
                  @change="handleAllCheck"
                />
              </th>
              <th width="400">商品信息</th>
              <th width="220">单价</th>
              <th width="180">数量</th>
              <th width="180">小计</th>
              <th width="140">操作</th>
            </tr>
          </thead>
          <!-- 商品列表 -->
          <tbody>
            <tr v-for="i in cartStore.cartList" :key="i.id">
              <td>
                <el-checkbox
                  :modelValue="i.selected"
                  @change="(selected) => handleCheck(i.id, selected)"
                />
              </td>
              <td>
                <div class="goods">
                  <RouterLink :to="`/detail/${i.goodId || i.id}`">
                    <img
                      :src="typeof i.pic === 'string' ? i.pic : (i.good?.pic || i.picture || i.pic)"
                      alt=""
                      @error="handleImageError"
                    />
                  </RouterLink>
                  <div>
                    <p class="name ellipsis">
                      {{ i.name || i.good?.name }}
                    </p>
                    <p class="attr ellipsis" v-if="i.attrsText">
                      {{ i.attrsText }}
                    </p>
                  </div>
                </div>
              </td>
              <td class="tc">
                <p>&yen;{{ i.price }}</p>
              </td>
              <td class="tc">
                <el-input-number
                  :min="1"
                  :max="99"
                  :modelValue="i.count"
                  controls-position="right"
                  size="small"
                  @change="(count) => handeChangeCount(i.id, count)"
                />
              </td>
              <td class="tc">
                <p class="f16 red">&yen;{{ (i.price * i.count).toFixed(2) }}</p>
              </td>
              <td class="tc">
                <p>
                  <el-popconfirm
                    title="确认删除吗?"
                    confirm-button-text="确认"
                    cancel-button-text="取消"
                    @confirm="deleteCart(i)"
                  >
                    <template #reference>
                      <a href="javascript:;">删除</a>
                    </template>
                  </el-popconfirm>
                </p>
              </td>
            </tr>
            <tr v-if="cartStore.cartList.length === 0">
              <td colspan="6">
                <div class="cart-none">
                  <el-empty description="购物车列表为空">
                    <el-button type="primary" @click="$router.push('/')"
                      >随便逛逛</el-button
                    >
                  </el-empty>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <!-- 操作栏 -->
      <div class="action">
        <div class="batch">
          共 {{ cartStore.allCount }} 件商品，已选择
          {{ cartStore.selectedCount }} 件，商品合计：
          <span class="red">¥ {{ cartStore.selectedPrice.toFixed(2) }} </span>
        </div>
        <div class="total">
          <el-button
            size="large"
            type="primary"
            :disabled="cartStore.selectedCount === 0"
            @click="goToCheckout"
            >下单结算</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.xtx-cart-page {
  margin-top: 20px;

  .cart {
    background: #fff;
    color: #666;

    table {
      border-spacing: 0;
      border-collapse: collapse;
      line-height: 24px;

      th,
      td {
        padding: 10px;
        border-bottom: 1px solid #f5f5f5;

        &:first-child {
          text-align: left;
          padding-left: 30px;
          color: #999;
        }
      }

      th {
        font-size: 16px;
        font-weight: normal;
        line-height: 50px;
      }
    }
  }

  .cart-none {
    text-align: center;
    padding: 120px 0;
    background: #fff;

    p {
      color: #999;
      padding: 20px 0;
    }
  }

  .tc {
    text-align: center;

    a {
      color: $xtxColor;
    }

    .xtx-numbox {
      margin: 0 auto;
      width: 120px;
    }
  }

  .red {
    color: $priceColor;
  }

  .green {
    color: $xtxColor;
  }

  .f16 {
    font-size: 16px;
  }

  .goods {
    display: flex;
    align-items: center;

    img {
      width: 100px;
      height: 100px;
      object-fit: cover;
      border-radius: 4px;
    }

    > div {
      width: 280px;
      font-size: 16px;
      padding-left: 10px;

      .name {
        font-weight: 500;
        margin-bottom: 5px;
      }

      .attr {
        font-size: 14px;
        color: #999;
      }
    }
  }

  .action {
    display: flex;
    background: #fff;
    margin-top: 20px;
    height: 80px;
    align-items: center;
    font-size: 16px;
    justify-content: space-between;
    padding: 0 30px;

    .xtx-checkbox {
      color: #999;
    }

    .batch {
      a {
        margin-left: 20px;
      }
    }

    .red {
      font-size: 18px;
      margin-right: 20px;
      font-weight: bold;
    }
  }

  .tit {
    color: #666;
    font-size: 16px;
    font-weight: normal;
    line-height: 50px;
  }
}
</style>
